<template>
    <div class="container-fluid">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
                        <el-menu-item index="1">文章</el-menu-item>
                        <el-menu-item index="2">视频</el-menu-item>
                    </el-menu>
                    <div class="card-body">
                        <div>
                            <form class="form-inline" onsubmit="return false;">
                                <div class="form-group">
                                    <label class="sr-only" for="example-if-password">请文章标题</label>
                                    <input class="form-control" type="text" id="example-if-password"
                                           name="example-if-password" placeholder="请文章标题" v-model="keyword">
                                </div>
                                <div class="form-group">
                                    <el-select v-model="status" placeholder="全部">
                                        <el-option
                                                v-for="item in options"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.value">
                                        </el-option>
                                    </el-select>
                                </div>
                                <div class="form-group">
                                    <button class="btn btn-success" type="submit" v-on:click="search()">筛选</button>
                                </div>
                            </form>
                        </div>

                        <div class="table-responsive" style="width: 100%;margin-top: 20px;" v-loading="loading">
                            <el-table
                                    :data="list"
                                    style="width: 100%"
                                    @sort-change='sortChange'
                                    :default-sort="{prop: '_id', order: 'descending'}"
                            >
                                <el-table-column
                                        label="ID"
                                        type="index"
                                        :index="indexMethod"
                                        align="center"
                                        width="35">
                                </el-table-column>
                                <el-table-column
                                        prop="title"
                                        label="文章标题"
                                        align="center"
                                        width="140">
                                    <template slot-scope="scope">
                                        <a :href="'/admin/article/'+scope.row._id+'/edit'" target="_blank" style="cursor:pointer;">{{scope.row.title}}</a>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                        prop="companyStr"
                                        label="所属公司"
                                        align="center"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="categoryStr"
                                        label="所属分类"
                                        align="center"
                                        width="70">
                                </el-table-column>
                                <el-table-column
                                        prop="userName"
                                        label="上传用户"
                                        align="center"
                                        width="80">
                                </el-table-column>
                                <el-table-column
                                        prop="officialAccount"
                                        label="来源公众号"
                                        align="center"
                                        width="100">
                                </el-table-column>
                                <el-table-column
                                        prop="status"
                                        label="状态"
                                        align="center"
                                        :formatter="formatStatus"
                                        width="60">
                                </el-table-column>
                                <el-table-column
                                        prop="wxView"
                                        label="浏览"
                                        align="center"
                                        sortable
                                        width="70">
                                </el-table-column>
                                <el-table-column
                                        prop="shareNum"
                                        label="分享"
                                        align="center"
                                        sortable
                                        width="70">
                                </el-table-column>
                                <el-table-column
                                        prop="created_at"
                                        label="上传时间"
                                        align="center"
                                        sortable
                                        width="146">
                                </el-table-column>
                                <el-table-column
                                        label="操作"
                                        align="center"
                                        width="180">
                                    <template slot-scope="scope">
                                        <span class="span-success"  @click="handleEdit(scope.row)">设置</span>

                                        <span class="span-success" @click="handlePush(scope.row._id,0)">取消推送
                                        </span>
                                    </template>

                                </el-table-column>
                            </el-table>

                            <nav style="margin-top: 20px">
                                <el-pagination
                                        layout="total, sizes, prev, pager, next"
                                        :total="total"
                                        :hide-on-single-page="pageActive"
                                        @size-change="handleSizeChange"
                                        :page-size="pageSize"
                                        :current-page="currentPage"
                                        :page-sizes="[10, 20, 30, 40]"
                                        @current-change="handleCurrentChange"
                                >
                                </el-pagination>
                            </nav>

                            <el-dialog title="文章设置" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
                                <el-form :model="form">

                                    <el-form-item label="" :label-width="formLabelWidth">
                                        <h5>{{articleTitle}}</h5>
                                    </el-form-item>


                                    <el-form-item label="关联分类" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.categoryName"
                                                :fetch-suggestions="querySearchAsync"
                                                placeholder="请输入内容"
                                                @select="handleQuerySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in categoryTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleIndustryClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>

                                    <el-form-item label="关联公司" :label-width="formLabelWidth">
                                        <el-autocomplete
                                                v-model="form.companyName"
                                                :fetch-suggestions="queryCompanyAsync"
                                                placeholder="请输入内容"
                                                @select="handleCompanySelect"
                                                style="width: 100%"
                                        ></el-autocomplete>
                                        <el-tag
                                                :key="tag.id"
                                                v-for="tag in companyTags"
                                                closable
                                                :disable-transitions="false"
                                                @close="handleCompanyClose(tag)">
                                            {{tag.value}}
                                        </el-tag>
                                    </el-form-item>
                                </el-form>
                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                                    <el-button type="primary" @click="submitSet">确 定</el-button>
                                </div>
                            </el-dialog>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        name: "ArticlePoolComponent",
        data() {
            return {
                url: '',
                keyword: '',
                pageActive: false,
                list: [],
                pageSize: 10,
                total: 0,
                currentPage: 1,
                loading: true,
                activeIndex: "1",
                options: [{
                    value: -1,
                    label: '全部'
                }, {
                    value: 1,
                    label: '已推送'
                }, {
                    value: 0,
                    label: '未推送'
                }],
                status: -1,
                form: {
                    name: '',
                    categoryName: '',
                    companyName: ''
                },
                categoryTags: [],
                categoryIds: [],
                companyTags: [],
                companyIds: [],
                dialogFormVisible: false,
                formLabelWidth: '120px',
                companies: [],
                restaurants: [],
                id: 0,
                order: 'desc',
                orderField: '_id',
                articleTitle:'',
                activeName:'second'
            }
        },
        methods: {
            search: function () {
                let self = this;
                let uri = 'article/post-list';
                self.loading = true;
                let postData = {
                    keyword: self.keyword,
                    page: self.currentPage,
                    limit: self.pageSize,
                    pushStatus: 1,
                    order: self.order,
                    orderField: self.orderField
                };
                axios.post(uri,postData).then(function (result) {
                    self.total = result.articles.total;
                    if (self.total > 0) {
                        self.pageActive = false;
                    } else {
                        self.pageActive = true;
                    }
                    self.list = result.articles.data;
                    self.loading = false;
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleSizeChange: function (pageSize) {
                this.pageSize = pageSize;
                this.search();
            },
            handleCurrentChange: function (val) {
                this.currentPage = val;
                this.search();
            },
            indexMethod: function (index) {
                return index + 1;
            },
            formatTitle: function (row, column) {
                return this.filterLength(row.title, 10);
            },
            formatCompany: function (row, column) {
                return this.filterLength(row.companyStr, 4);
            },
            formatIndustry: function (row, column) {
                return this.filterLength(row.categoryStr, 4);
            },
            formatStatus: function (row, column) {
                return !row.pushRealStatus ? '未推送' : '已推送';
            },
            handleDelete: function (row) {
                let self = this;
                let tipStr = "此操作将永久删除“" + row.title + "”, 是否继续?";
                self.$confirm(tipStr, '文章删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.deleteRequire(row._id)
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },//查询分类
            async queryIndustry(keyword = '') {
                let self = this;
                let uri = "category/search/"+keyword;
                axios.get(uri).then(function (result) {
                    self.restaurants = result.list;
                });
            },
            async queryCompany(keyword = '') {
                let self = this;
                let uri = "company/search/"+keyword;
                axios.get(uri).then(function (result) {
                    self.companies = result.list;
                });
            },
            deleteRequire: function (id) {
                let self = this;
                let uri = "article/" + id;
                axios.delete(uri).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            async querySearchAsync(queryString, cb) {
                await this.queryIndustry(queryString);
                var restaurants = this.restaurants;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleQuerySelect(item) {
                if (item && this.categoryIds.indexOf(item.id) === -1) {
                    this.categoryTags.push(item);
                    this.categoryIds.push(item.id);
                }
                this.form.categoryName = '';
            },
            async queryCompanyAsync(queryString, cb) {

                await this.queryCompany(queryString);
                let restaurants = this.companies;
                var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
                clearTimeout(this.timeout);
                this.timeout = setTimeout(() => {
                    cb(results);
                }, 1000 * Math.random());
            },
            handleCompanySelect(item) {
                if (item && this.companyIds.indexOf(item.id) === -1) {
                    this.companyTags.push(item);
                    this.companyIds.push(item.id);
                }
                this.form.companyName = '';
            },
            handleIndustryClose(tag) {
                this.categoryTags.splice(this.categoryTags.indexOf(tag), 1);
                this.categoryIds.splice(this.categoryIds.indexOf(tag.id), 1);
            },
            handleCompanyClose(tag) {
                this.companyTags.splice(this.companyTags.indexOf(tag), 1);
                this.companyIds.splice(this.companyIds.indexOf(tag.id), 1);
            },
            handleEdit(item) {
                this.dialogFormVisible = true;
                //this.categoryTags = item.categoryNames;
                this.form.categoryName = '';
                this.form.companyName = '';
                this.companyIds = [];
                this.companyTags = [];
                this.categoryIds = [];
                this.categoryTags = [];
                this.articleTitle = item.title;

                let data = item;
                this.categoryTags = data.categoryNames;

                data.categoryNames.forEach((item) => {
                    this.categoryIds.push(item.id)
                });
                this.companyTags = data.companies;
                data.companies.forEach((item) => {
                    this.companyIds.push(item.id)
                });
                this.id = item._id;
            },
            submitSet() {
                let self = this;
                let categoryIds = this.categoryIds;
                let companyIds = this.companyIds;
                /*if (categoryIds.length > 0 && companyIds.length) {
                    self.$message.error('不能同时选择分类和公司！');
                    return;
                }*/
                self.loading = true;
                let uri = "article/set/" + self.id;
                let data = {companyIds: companyIds, categoryIds: categoryIds};
                self.dialogFormVisible = false;
                axios.put(uri, data).then(function (result) {
                    self.search();
                });
            },
            openEdit(id) {
                this.openUri('article/' + id + '/edit');
            },
            sortChange(item) {
                let order = "asc";
                this.orderField = item.prop;
                if (item.order === 'descending') {
                    order = "desc";
                }
                this.order = order;
                this.search();
            },
            handlePush: function (id,pushStatus) {
                let self = this;
                let tipStr = "确定该操作, 是否继续?";
                self.$confirm(tipStr, '推送设置', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    self.pushRequire(id,pushStatus)
                }).catch(() => {
                    self.$message({
                        type: 'info',
                        message: '已取消操作'
                    });
                });
            },
            pushRequire: function (id,pushStatus) {
                let self = this;
                let uri = "article/push/" + id + '/' + pushStatus;
                self.loading = true;
                axios.get(uri).then(function (result) {
                    self.search();
                }).catch(function (error) {
                    self.loading = false;
                });
            },
            handleSelect(key, keyPath){
                this.openUri('push-pool/video');
            }
        },
        mounted() {
            this.search();
            this.queryIndustry();
            this.queryCompany();
        },
        filters: {
            titleFormatter(title) {
                if (title.length >= 10) {
                    return title.substring(0, 10) + '...';
                }
                return title.length === 0 ? '--' : title;
            }
        }
    }
</script>

<style scoped>

</style>
